﻿using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WINPE_TOOLBOX.Properties;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static WINPE_TOOLBOX.ReadOnlyConfig;

namespace WINPE_TOOLBOX.MainPage
{
   

    public partial class FirstPage : UIPage
    {
        private Aria2Downloader downloader;
        Config config = Config.Instance; // 访问全局配置实例

        public FirstPage()
        {
            InitializeComponent();
            downloader = new Aria2Downloader();
            downloader.ProgressUpdated += OnProgressUpdated;
            downloader.DownloadFinished += OnDownloadFinished;
                    // 使窗体能够接收键盘事件
            this.KeyPreview = true;
            this.KeyDown += Form_KeyDownAsync;
        }

        private async void Form_KeyDownAsync(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                await downloader.StopDownloadAsync(AppDomain.CurrentDomain.BaseDirectory + "resources\\files\\pe", "*.*");
                //MessageBox.Show("下载已取消。");
                await FirstPage_Load(this, EventArgs.Empty);
            }
        }
        private void OnProgressUpdated(string speed, int percentage,string totalSize, string downloadedSize)
        {
            //Console.WriteLine("OnProgressUpdated triggered");
            Invoke(new Action(() =>
            {
                Label1.Text = "正在下载......";
                down_status_label.Text = "准备下载";
                down_status_label.Text = $"速度:{speed} 状态:({totalSize}/{downloadedSize}) 已完成:{percentage}%";
                progressBar1.Value = percentage;
            }));
        }

        private void OnDownloadFinished(string message)
        {
            //Console.WriteLine("OnDownloadFinished triggered");
            Invoke(new Action(async () =>
            {
                Label1.Text = message;
                down_status_label.Text = message;
                progressBar1.Value = 0;
                down_status_panel.Visible = false;
                await FirstPage_Load(this, EventArgs.Empty);

            }));
        }

        private void FirstPage_LoadHandler(object sender, EventArgs e)
        {
            // 调用异步加载方法
            _ = FirstPage_Load(sender, e);
        }
        private async Task FirstPage_Load(object sender, EventArgs e)
        {
            await Check.CheckPEResAsync();
            //List<string> testpe = await Utils.TraverseFiles(_resource.Pe, "*.7z");
            //config.Resources.Pe.All = await Utils.TraverseFiles(_resource.Pe, "*.7z");
            //MessageBox.Show(string.Join(Environment.NewLine, testpe));
            //MessageBox.Show(config.State.Install);
            if (config.State.Install == "noDown")
            {
                noDownPanel.Visible = true;
                noSetupPanel.Visible = false;
            }
            else if (config.State.Install == "noSetup")
            {
                noSetupPanel.Visible = true;
                noDownPanel.Visible = false;
                Label1.Text = "资源检测已就绪,但并未检测到已有WINPE的安装,请选择方式开始安装";

            }
            else if (config.State.Install == "ready")
            {
                noDownPanel.Visible = false ;
                noSetupPanel.Visible = false;
                readyPanel.Visible = true ;
                Label1.Text = "你的WINPE已准备就绪,你可以进行更改";
            }

        }

        private async void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            string pe_download_api = GlobalUrl.API + GlobalUrl.BtwiseUpdate;
            string pe_download_url = await GetDownloadUrlAsync(pe_download_api);
            string saveDir = AppDomain.CurrentDomain.BaseDirectory + "resources\\files\\pe";
            if (string.IsNullOrEmpty(pe_download_url))
            {
                MessageBox.Show("无法获取下载地址。");
                return;
            }
            //_aria2.Start(pe_download_url, saveDir, "240201.7z", UpdateDownloadStatus);
            down_status_panel.Visible = true;
            downloader.StartDownload(pe_download_url, saveDir, "240201.7z");

        }

        private void Downloader_DownloadProgressChanged(int completedLength, int totalLength, string status)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUI(completedLength, totalLength, status)));
            }
            else
            {
                UpdateUI(completedLength, totalLength, status);
            }
        }
        private void UpdateUI(int completedLength, int totalLength, string status)
        {
            Label1.Text = "开始下载...";
            down_status_label.Text = $"{completedLength}/{totalLength} {status}%";
            progressBar1.Maximum = totalLength > 0 ? totalLength : 1;
            progressBar1.Value = completedLength;
        }
        private async Task<string> GetDownloadUrlAsync(string apiUrl)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    string json = await client.GetStringAsync(apiUrl);
                    JObject data = JObject.Parse(json);
                    return data["data"]?["pe"]?["download_url"]?.ToString();
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("Error fetching download URL: " + ex.Message);
                    return null;
                }
            }
        }

        private async void FirstPage_FormClosing(object sender, FormClosingEventArgs e)
        {
            await downloader.StopDownloadAsync(AppDomain.CurrentDomain.BaseDirectory + "resources\\files\\pe", "*.*");
        }
    }
}
